package com.zh.admin.product.controller;

import com.zh.admin.product.service.ProductsAdminService;
import com.zh.pojo.Products;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

@Controller
@RequestMapping("/admin/productAdmin")
public class ProductsAdminController {

    @Autowired
    private ProductsAdminService productsAdminService;

    @Value("D:\\文件\\第六学期--大三（下）\\Java EE 企业项目开发\\bookstore\\web\\productImg\\")
    private String ABSOULTE_PATH;

    /**
     * 查询全部商品
     * @param model
     * @return
     */
    @RequestMapping("/queryProductsAll")
    public String queryProductsAll(Model model,HttpServletRequest request){
        List<Products> products = productsAdminService.selectProductsAll();
        model.addAttribute("products",products);
        return "admin/products/list";
    }

    /**
     * 按照id查询一个商品信息
     * @param id
     * @return
     */
    @RequestMapping("/queryProductsById")
    public String queryProductsById(String id,Model model){
        Products products = productsAdminService.selectProductsById(id);
        model.addAttribute("p",products);
        return "admin/products/edit";
    }

    /**
     * 修改一条商品信息
     * @param products
     * @return
     */
    @RequestMapping("/modifyProducts")
    public String modifyProducts(Products products,MultipartFile file,HttpServletRequest request){
//        System.out.println(products);
        if(file != null){
            String imgUrl = products.getImgurl().substring(12);
            String path = request.getContextPath()+"/productImg/";
            try {
//                file.transferTo(new File(path+imgUrl));
                file.transferTo(new File(ABSOULTE_PATH+imgUrl));
                products.setImgurl("/productImg/"+imgUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        int i = productsAdminService.updateProducts(products);
        return "redirect:queryProductsAll";
    }

    /**
     * 删除一条商品信息
     * @param id
     * @return
     */
    @RequestMapping("/removeProductsById")
    public String removeProductsById(String id,HttpSession session){
//        System.out.println(id);
        Products product = productsAdminService.selectProductsById(id);
        int i = productsAdminService.deleteProductsById(id);
//        String path = String.valueOf(session.getServletContext().getResourcePaths(product.getImgurl()));
//        System.out.println("remove -- "+path);
        if(i>0){
            String path = ABSOULTE_PATH+product.getImgurl().substring(12);
            File file = new File(path);
            if(file.exists()){
                file.delete();
            }
        }
        return "redirect:queryProductsAll";
    }

    /**
     * 添加一条商品信息
     * @param products
     * @return
     */
    @RequestMapping("/addProducts")
    public String addProducts(Products products, MultipartFile file,HttpServletRequest request){
        products.setId(UUID.randomUUID().toString());
        String originalFilename = file.getOriginalFilename();
        String imgUrl = UUID.randomUUID()+"-"+originalFilename;
//        System.out.println(imgUrl);

        String path = request.getContextPath()+"/productImg/";
//        System.out.println("path = "+path+imgUrl);
        try {
//            file.transferTo(new File(path+imgUrl));
            file.transferTo(new File(ABSOULTE_PATH+imgUrl));
            products.setImgurl("/productImg/"+imgUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        System.out.println("OK -- "+products);
        int i = productsAdminService.insertProducts(products);
        return "redirect:queryProductsAll";
    }

    /**
     * 条件查询商品
     * @param minprice 最小价格
     * @param maxprice 最大价格
     * @param model
     * @return
     */
    @RequestMapping("/queryProductsCondition")
    public String queryProductsCondition(Products products,String minprice,String maxprice, Model model){
        if(products.getId()!=null&&products.getId().length() == 0) products.setId(null);
        if(products.getName()!=null&&products.getName().length() == 0) products.setName(null);
        if(products.getCategory()!=null&&products.getCategory().length() == 0) products.setCategory(null);
        double min=-1;
        double max=-1;
//        System.out.println("length = " + minprice.length() + " -- " + maxprice.length());
        model.addAttribute("products",null);
        model.addAttribute("p",products);
        model.addAttribute("minprice",minprice);
        model.addAttribute("maxprice",maxprice);

        if(minprice.length()>0&&checkStringIsDouble(minprice.toCharArray())&&
                maxprice.length()>0&&checkStringIsDouble(maxprice.toCharArray())){
            min = Double.parseDouble(minprice);
            max = Double.parseDouble(maxprice);
        }
        List<Products> products1 = productsAdminService.selectProductsCondition(products,min,max);
        model.addAttribute("products",products1);
//        System.out.println("queryProductsCondition = "+products+"--"+min+"--"+max);

        return "admin/products/list";
    }

    /**
     * 文档下载
     * @param year
     * @param month
     * @param response
     * @return
     */
    @RequestMapping("/queryHotData")
    public void queryHotData(String year, String month, HttpServletResponse response) {
        Integer y = -1;
        Integer m = 0;
        if(year.length() <= 0) year = null;
        if(year!=null&&checkStringIsInteger(year.toCharArray())) y = Integer.parseInt(year);
        if(month!=null&&checkStringIsInteger(month.toCharArray())) m = Integer.parseInt(month);


        List<Products> products = productsAdminService.selectHotData(y, m);

        List<String> title = new ArrayList<>();
        title.add("编号,");
        title.add("名称,");
        title.add("价格,");
        title.add("类别,");
        title.add("描述,");
        title.add("销量");

        File writeFile = new File("D:\\dowload.csv");
        try{
            //第二步：通过BufferedReader类创建一个使用默认大小输出缓冲区的缓冲字符输出流
            BufferedWriter writeText = new BufferedWriter(new FileWriter(writeFile));
            //第三步：将文档的下一行数据赋值给lineData，并判断是否为空，若不为空则输出
            for (String t : title) {
                writeText.write(t);
            }
            writeText.newLine();    //换行

            for (Products product : products) {
                writeText.write(product.getId()+","+product.getName()+","+
                        product.getPrice()+","+product.getCategory()+","+
                        product.getDescription()+","+product.getPnum());
                writeText.newLine();
            }
            //使用缓冲区的刷新方法将数据刷到目的地中
            writeText.flush();
            //关闭缓冲区，缓冲区没有调用系统底层资源，真正调用底层资源的是FileWriter对象，缓冲区仅仅是一个提高效率的作用
            //因此，此处的close()方法关闭的是被缓存的流对象
            writeText.close();
            download(response);
        }catch (FileNotFoundException e){
            System.out.println("没有找到指定文件");
        }catch (IOException e){
            System.out.println("文件读写出错");
        }
    }

    private boolean checkStringIsDouble(char[] s){
        boolean decimalPoint = true;
        for (int i = 0; i < s.length; i++) {
            if(decimalPoint&&s[i]=='.'){
                decimalPoint = false;
            }else if((s[i]>'9'||s[i]<'0')){
                return false;
            }
        }
        return true;
    }

    private boolean checkStringIsInteger(char[] s){
        for (int i = 0; i < s.length; i++) {
            if((s[i]>'9'||s[i]<'0')){
                return false;
            }
        }
        return true;
    }

    private boolean download(HttpServletResponse res) throws IOException {
        File file = new File("D:\\dowload.csv");
        String fileName = UUID.randomUUID()+".csv";
        res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }
}
